package com.lina.serverbluetoothlina;
import java.util.HashMap;
import java.util.Locale;
import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

public class Speaker implements OnInitListener {
	 
    private TextToSpeech tts; 
    private boolean ready = false;
    private boolean allowed = false;
     
    public Speaker(Context context){
        tts = new TextToSpeech(context, this);      
    }   
     
    public boolean isAllowed(){
        return allowed;
    }
     
    public void allow(boolean allowed){
        this.allowed = allowed;
    }
    //The OnInitListener interface has only one method, onInit. This method is called when the TTS engine has been initialized.
    //The status parameter lets us know if the initialization was successful. Once we know that the 
    //initialization was successful, we set the language of the TTS engine. This is important to produce speech that is comprehensible.
    @Override
    public void onInit(int status) {
        if(status == TextToSpeech.SUCCESS){
            // Change this to match your
            // locale
            tts.setLanguage(Locale.US);
            ready = true;
        }else{
            ready = false;
        }
    }
    //Next, we add a method named speak, which uses the engine to read out any text that is passed to it.
    //Before doing so, it checks if both the allowed and the ready values are true. The speech it generates 
    //is placed in the notification stream.
    public void speak(String text){
        
        // Speak only if the TTS is ready
        // and the user has allowed speech
         
        if(ready && allowed) {
            HashMap<String, String> hash = new HashMap<String,String>();
            hash.put(TextToSpeech.Engine.KEY_PARAM_STREAM, 
                    String.valueOf(AudioManager.STREAM_NOTIFICATION));
            tts.speak(text, TextToSpeech.QUEUE_ADD, hash);
        }
    }
    //We then add a method that plays silence for a specified duration. Using this method, we can add 
    //pauses to the speech to make it sound a little clearer. Add the following code to the implementation:
    public void pause(int duration){
        tts.playSilence(duration, TextToSpeech.QUEUE_ADD, null);
    }
    // Free up resources when the TTS engine is no longer needed.
    public void destroy(){
        tts.shutdown();
    }
}
